from app import db, login
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin, login_manager


class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True)
    password_hash = db.Column(db.String(128))
    last_login_at = db.Column(db.DateTime, default=datetime.utcnow)

    profile = db.relationship('Profile', backref='user', lazy='dynamic')

    def __repr__(self):
        return '<User {}>'.format(self.username)

    @property
    def password(self):
        return self.password_hash

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)


@login.user_loader
def load_user(user_id):
    return User.query.get(user_id)


class Profile(db.Model):
    __table_args__ = (
        db.PrimaryKeyConstraint('user_id'),
    )

    user_id = db.Column(db.ForeignKey('user.id'))
    nickname = db.Column(db.String(125))
    tel = db.Column(db.String(13))

    def __repr__(self):
        return '<Profile {}, {}>'.format(self.user_id, self.nickname)
